<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-01-10
 * @Time: 16:17
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： DynamicFlow.php
 */
namespace app\common\model;


use app\common\model\dynamic\DynamicFlowItem;
use think\Db;
use think\db\Query;
use think\Log;
use think\Model;

/**
 * Class DynamicFlow
 * @package app\common\model
 *
 * @property mixed df_id
 * @property mixed df_class
 * @property mixed df_type
 * @property mixed df_time
 * @property mixed df_value
 * @property mixed df_delete
 * @property mixed df_source
 * @property mixed df_isfee
 * @property mixed df_isnew
 *
 */
class DynamicFlow extends Model
{
    protected $table = 'dynamic_flow';
    protected $pk = 'df_id';
    protected $field = [
        'df_id',
        'df_class',
        'df_type',
        'df_time',
        'df_value',
        'df_delete',
        'df_source',
        'df_isfee',
        'df_isnew',
    ];


    const CLASS_COLUMN      = 1;
    const CLASS_ESSAY       = 2;
    const CLASS_LIVE        = 3;
    const CLASS_CURRICULUM  = 4;
    const CLASS_TOPIC_LIVE  = 5;
    private static $ClassNames = [
        self::CLASS_COLUMN      => '专栏',
        self::CLASS_ESSAY       => '文章',
        self::CLASS_LIVE        => '视频直播',
        self::CLASS_CURRICULUM  => '课程',
        self::CLASS_TOPIC_LIVE  => '图文直播',
    ];
    public static function getClassName($classId) {
        return self::$ClassNames[$classId]['name'] ?? '';
    }
    public static function getClassNames(): array {
        return self::$ClassNames;
    }

    const TYPE_RICH_TEXT    = 1;
    const TYPE_AUDIO        = 2;
    const TYPE_VIDEO        = 3;
    const TYPE_LIVE         = 4;
    const TYPE_CURRICULUM   = 5;
    const TYPE_TOPIC_LIVE        = 6;
    private static $TypeNames = [
        self::TYPE_RICH_TEXT    => '图文',
        self::TYPE_AUDIO        => '语音',
        self::TYPE_VIDEO        => '视频',
        self::TYPE_LIVE         => '直播视频',
        self::TYPE_CURRICULUM   => '课程',
        self::TYPE_TOPIC_LIVE        => '图文直播',
    ];
    public static function getTypeName($typeId) {
        return self::$TypeNames[$typeId] ?? '';
    }
    public static function getTypeNames() {
        return self::$TypeNames;
    }

    const SOURCE_SYSTEM      = 0; // 0-系统生成
    const SOURCE_ADMIN      = 1; // 1-老师后台
    const SOURCE_TEACHER    = 2; // 2-运营后台

    /**
     * @inheritdoc
     */
    public function save($data = [], $where = [], $sequence = null)
    {
        $this->encodeJSON();
        return parent::save($data, $where, $sequence);
    }

    /**
     * 动态管理列表
     *
     * @param integer       $limit
     * @param integer       $offset
     * @param null|integer  $class
     * @param null|integer  $type
     * @return static[]
     */
    public static function manageList($limit, $offset, $class = null, $type = null) {

        $list = static::all(function (Query $query) use ($limit,$offset,$class,$type) {

            if (null !== $class && isset(self::$ClassNames[$class])) {
                $query->where('df_class','=',$class);
            }
            if (null !== $type && isset(self::$TypeNames[$type])) {
                $query->where('df_type','=',$type);
            }

            $query->limit($offset, $limit);
        });

        foreach ($list as $item) {
            $item->decodeJSON();
        }

        return $list;
    }

    /**
     * 统计
     *
     * @param null $class
     * @param null $type
     * @return int
     */
    public static function manageCount($class = null, $type = null) {
        $filters = '';
        $params = [];
        if (null !== $class) {
            $filters .= ' AND df_class=:dfc ';
            $params['dfc'] = $class;
        }
        if (null !== $type) {
            $filters .= ' AND df_type=:dft ';
            $params['dft'] = $type;
        }
        $sql = <<<SQL
SELECT count(*) c FROM dynamic_flow WHERE TRUE {$filters}
SQL;
        $re = Db::query($sql, $params);

        return $re[0]['c'] ?? 0;
    }

    /**
     * 批量删除动态
     *
     * @param array $ids
     */
    public static function deleteIn(array $ids) {
        if (count($ids) == 0) return;

        $fields = implode(',', array_fill(0,count($ids),'?'));
        $sql = "DELETE FROM dynamic_flow WHERE df_id IN ($fields)";
        Db::execute($sql, $ids);
    }

    /**
     * 删除动态
     *
     * @param int $itemClass
     * @param int $itemId
     * @return int
     */
    public static function del(int $itemClass, int $itemId) {
        $sql = <<<SQL
DELETE FROM dynamic_flow
WHERE df_class=:df_class AND 
df_value @> :val
RETURNING *
SQL;
        $params = [
            'df_class' => $itemClass,
            'val' => '{"item_id":'.$itemId.'}',
        ];
        $re = Db::execute($sql, $params);
        return $re;
    }

    public function encodeJSON() {
        if (isset($this->df_value) && (is_array($this->df_value) || is_object($this->df_value)))
            $this->df_value = json_encode($this->df_value,JSON_UNESCAPED_UNICODE);
    }
    public function decodeJSON() {
        if (isset($this->df_value) && is_string($this->df_value))
            $this->df_value = json_decode($this->df_value);
    }

    /**
     * @deprecated
     * 添加动态信息
     *
     * @param int $class
     * @param int $type
     * @param int $timestamp
     * @param DynamicFlowItem $content
     * @param int $source
     * @param bool $isFee
     * @return false|int
     */
    public static function addDynamic(int $class, int $type, int $timestamp, DynamicFlowItem $content, int $source, bool $isFee = false) {
        $model = new static();
        $model->df_class = $class;
        $model->df_type = $type;
        $model->df_time = $timestamp;
        $model->df_value = json_encode($content,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
        $model->df_source = $source;
        $model->df_isfee = $isFee;
        return $model->save();
    }

    /**
     * @deprecated
     * createDynamic
     * 创建名师动态信息流
     *
     * @author zhengkai
     * @date 2018-01-10
     *
     * @param int $class 信息分类
     * @param int $type 信息类型
     * @param int|string $timestamp 信息发布时间（时间戳）
     * @param array $content 信息数据
     * @param int $source 信息来源
     * @param boolean $isFee 是否收费标识
     * @return bool
     */
    public function createDynamic($class, $type, $timestamp, $content=array(), $source, $isFee='false')
    {
        $data = [
            'df_class' => $class,
            'df_type' => $type,
            'df_time' => $timestamp,
            'df_value' => json_encode($content, JSON_UNESCAPED_UNICODE),
            'df_source' => $source,
            'df_isfee' => $isFee
        ];

        Db::startTrans();
        try {

            Db::query("insert into dynamic_flow (df_class, df_type, df_time, df_value, df_source, df_isfee) values ({$data['df_class']}, {$data['df_type']}, '{$data['df_time']}', '{$data['df_value']}', {$data['df_source']}, {$data['df_isfee']})");

            Db::commit();

            return true;
        } catch (\Exception $e) {
            Db::rollback();

            Log::error('创建名师动态信息流错误信息：'.$e);

            return false;
        }
    }

}
